package com.quanxiaoha.weblog.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.quanxiaoha.weblog.admin.service.AdminAnnouncementService;
import com.quanxiaoha.weblog.common.Response;
import com.quanxiaoha.weblog.common.domain.dos.AnnouncementDO;
import com.quanxiaoha.weblog.common.domain.dos.AnnouncementVO;
import com.quanxiaoha.weblog.common.domain.mapper.AnnouncementMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Objects;

@RestController
@RequestMapping("/frontend/announcement")
public class AnnouncementController {

    @Autowired
    private AdminAnnouncementService announcementService;

    @Resource
    private AnnouncementMapper announcementMapper;

    /**
     * 获取启用的公告
     *
     * @return
     */
    @PostMapping("/get")
    public Response<AnnouncementVO> getAnnouncement() {
        // 查询启用状态的公告（状态为1且未删除）
        LambdaQueryWrapper<AnnouncementDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AnnouncementDO::getIsEnabled, 1)
                .eq(AnnouncementDO::getIsDeleted, 0)
                .orderByDesc(AnnouncementDO::getCreateTime) // 按创建时间倒序
                .last("LIMIT 1"); // 只取最新的一个

        AnnouncementDO announcementDO = announcementMapper.selectOne(wrapper);

        // 如果没有找到公告，返回空结果
        if (Objects.isNull(announcementDO)) {
            return Response.success(null);
        }

        // 转换为VO对象
        AnnouncementVO announcementVO = new AnnouncementVO();
        BeanUtils.copyProperties(announcementDO, announcementVO);

        return Response.success(announcementVO);
    }
}